package com.kewu.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author wangning
 * @create 2024-05-23-9:21
 */
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context = null;

    public SpringContextUtil() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(String name) {
        if (context.containsBean(name)) {
            return context.getBean(name);
        }
        return null;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        if (context.containsBean(name)) {
            return context.getBean(name, requiredType);
        }
        return null;
    }
}
